<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\shop\controller;

use controller\BasicShop;
use service\DataService;
use think\Db;
use think\Validate;

/**
 * 微信粉丝管理
 * Class Fans
 * @package app\wechat\controller
 * @author Anyon <zoujingli@qq.com>
 * @date 2017/03/27 14:43
 */
class Member extends BasicShop
{

    /**
     * 定义当前默认数据表
     * @var string
     */
    public $table = 'store_member';

    /**
     * 显示粉丝列表
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function index()
    {
        $this->title = '用户列表';
        $get = $this->request->get();

        $db = Db::table('store_member');

        $db->where('shop_id', $this->user['id']);

        $levellist = Db::name('sys_level')->select();
        $this->assign('level',$levellist);
        if (isset($get['create_at']) && $get['create_at'] !== '') {
            list($start, $end) = explode(' - ', $get['create_at']);
            $db->whereBetween('create_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
            $num = Db::name('store_member');
            $num->whereBetween('create_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
            $count['time'] = 2;
            $usrnum1 = [
                'shop_id' => $this->user['id'],
                'member_level' => 1
            ];
            $usrnum2 = [
                'shop_id' => $this->user['id'],
                'member_level' => 2
            ];
            $count['vip'] = $num->where($usrnum2)->count();
            $count['yubei'] = $num->where($usrnum1)->count();
        }else{
            $count['time'] = 3;
            $usrnum1 = [
                'shop_id' => $this->user['id'],
                'member_level' => 1
            ];
            $usrnum2 = [
                'shop_id' => $this->user['id'],
                'member_level' => 2
            ];
            $count['vip'] = Db::name('store_member')->where($usrnum2)->count();
            $count['yubei'] = Db::name('store_member')->where($usrnum1)->count();
        }
        $this->assign('count',$count);

        if (isset($get['nickname']) && $get['nickname'] !== '') {
            $db->where('nickname', 'like',"%{$get['nickname']}%");
        }
        if (isset($get['phone']) && $get['phone'] !== '') {
            $db->where('phone', 'like',"%{$get['phone']}%");
        }
        if (isset($get['member_level']) && $get['member_level'] !== '') {
            $db->where('member_level', '=',$get['member_level']);
        }
        return parent::_list($db->order('create_at desc'));
    }
    public function _index_data_filter( &$data )
    {
        foreach($data as &$v) {
            $v['member_level_info'] = Db::name('sys_level')->where(['id' => $v['member_level']])->value('title');
            $v['team_num'] = Db::query("SELECT count(*) as sub_person_count  FROM `store_member` WHERE FIND_IN_SET({$v['id']},first_leader)")[0]['sub_person_count'];
            $v['company'] = Db::name('store_shops')->where(['id'=>$v['shop_id']])->find();
        }
        $sys_level = Db::name('sys_level')->select();
        $this->assign('sys_level',$sys_level);
    }

    public function carid(){
        $this->title = "历史车牌";
        $get = input('get.');
        $db = Db::name('store_member_carid')
            ->alias('a')
            ->join('store_member b','a.uid = b.id')
            ->field('b.truename,a.id,a.sheng,a.carid,a.addtime');
        if (isset($get['id']) && $get['id'] !== '' ){
            $where['uid'] = $get['id'];
            $db->where($where);
        }

        return parent::_list($db->order('id desc'));
    }


    /**
     * 列表数据处理
     * @param array $list
     */
    public function add()
    {
        $levellist = Db::name('sys_level')->select();
        $this->assign('level',$levellist);
        return $this->_form($this->table, 'form');
    }


    public function team(){
        $this->title = '用户中心';
        $get = $this->request->get();
        $db = Db::name('store_member');
        if (isset($get['id']) && $get['id'] != '') {
            $where['first_leader'] = $get['id'];
            $db->where($where);
        }


        $levellist = Db::name('sys_level')->select();
        $this->assign('level',$levellist);
        if (isset($get['create_at']) && $get['create_at'] != ''){
            list($start, $end) = explode(' - ', $get['create_at']);
            $db->whereBetween('create_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
        }


        foreach (['phone', 'member_level','creat_at'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }
        return parent::_list($db->order('id desc'));
    }

    
    public function edit()
    {
        $levellist = Db::name('sys_level')->select();
        $this->assign('level',$levellist);
        return $this->_form($this->table, 'form');
    }

    /**
     * 用户禁用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbid()
    {
        if (in_array('10000', explode(',', $this->request->post('id')))) {
            $this->error('系统超级账号禁止操作！');
        }
        if (DataService::update($this->table)) {
            $this->success("用户禁用成功！", '');
        }
        $this->error("用户禁用失败，请稍候再试！");
    }

    /**
     * 用户禁用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resume()
    {
        if (DataService::update($this->table)) {
            $this->success("用户启用成功！", '');
        }
        $this->error("用户启用失败，请稍候再试！");
    }

  

    public function getTreeMember($member_id =0){
        $list = [];
        $users =    Db::name('store_member a')
            ->field('a.id,a.nickname,a.create_at,a.phone,a.account_money,b.title,a.create_at')
            ->join('sys_level b',"a.member_level = b.id")
            ->where(['a.first_leader'=>$member_id])->select();
        if (!empty($users) && check_arr($users)) {
            foreach ($users as $k => &$v) {
                $v['children'] = $this->getTreeMember($v['id']);
                $list[] = $v;
            }
        }
        return $list;
    }

    //身份认证审核
    public function idaudit()
    {
        $this->title = '身份认证管理';
        $get = $this->request->get();
        $db = Db::name("store_member_idcard");
        $where = array();
        if (isset($get['type']) && $get['type'] != '') {
            $where['status'] = $get['type'];
            $db->where($where);
        }
//        sm($get);
        if (isset($get['name']) && $get['name'] != '') {
            $where['uid'] = Db::name('store_member')->where(array('phone' => $get['name']))->value('id');
            $db->where($where);
        }
        $db->order('id desc');
       return parent::_list($db);
    }
    
    //身份认证操作

    public function idpass()
    {
        $param = input('param.');
        Db::startTrans();
        if($param['status'] == 1){
            $db[] = Db::name('store_member_idcard')->where(['id'=>$param['id']])->update(['status'=>$param['status']]);
            $db[] = mlog($param['uid'],'mining',sysconf('sharenoting'),'实名认证通过赠送分享算力'.sysconf('sharenoting').'个');
            $userInfo = Db::name('store_member')->where(['id'=>$param['uid']])->find();
            if($userInfo['first_leader'] > 0){
                $content = "推广{$userInfo['nickname']},获取到分享算力:10";
                $db[] = mlog($userInfo['first_leader'], 'mining', 10, $content, 'share_dig_spread');
            }
        }elseif($param['status'] == 2){
            $db[] = Db::name('store_member_idcard')->where(['id'=>$param['id']])->update(['status'=>$param['status']]);
        }

        if (check_arr($db)){
            Db::commit();
            $this->success('操作成功');
        } else{
            Db::rollback();
            $this->error('操作失败');
        }
    }
    
    
    
    /**
     * 分销树状关系
     */
    public function member_org()
    {
        set_time_limit(0);
        $users = Db::name('store_member');
        $id = $_GET['member_id'];
        $list = Db::name('store_member')->where([
            'first_leader' => $id
        ])->select();

        foreach ($list as $key => $v) {
            $list[$key]['share'] = get_share_num($v['id']);
            //$list[$key]['team_share'] = get_team_share_num($v['id']);
            //   $list[$key]['children'] = self::handleUser($v['id'], $layer);

        }

        // 伞下会员用户id
      //  $umbrella_member_ids = Db::name('store_member')->where('leaders', 'like', "%$id%")->column('id');



        return view('', [
            'id' => $id,
            'list' => $list,

        ]);
    }

    /**
     * 获取某个人下级元素
     */
    public function ajax_lower()
    {
        $id = $_GET['id'];
        $list = Db::name('store_member')->where([
            'first_leader' => $id
        ])->select();
        foreach ($list as $key => $v) {
            $list[$key]['share'] = get_share_num($v['id']);

        }

        return view('', [
            'list' => $list
        ]);
    }

    public function full()
    {
        $this->title = '全价保养记录';
        $get = $this->request->get();

        $db = Db::table('store_apply_record a')
            ->field('a.*,b.phone,b.nickname')
            ->join('store_member b',"a.uid = b.id")
            ->where(['type'=>'is_full_price']);


        if (isset($get['create_at']) && $get['create_at'] !== '') {
            list($start, $end) = explode(' - ', $get['create_at']);
            $db->whereBetween('a.addtime', ["{$start} 00:00:00", "{$end} 23:59:59"]);
        }

        if (isset($get['updatetime']) && $get['updatetime'] !== ''){
            $db->where('b.updatetime');
        }

        if (isset($get['nickname']) && $get['nickname'] !== '') {
            $db->where('b.nickname', 'like',"%{$get['nickname']}%");
        }

        if (isset($get['phone']) && $get['phone'] !== '') {
            $db->where('b.phone', 'like',"%{$get['phone']}%");
        }
        $db->where('a.shopid', $this->user['id']);
        return parent::_list($db->order('a.addtime desc'));
    }


    public function order(){
        if ($this->request->post()){
            $data = input('post.');
            $validate = Validate::make([
                'id' => 'require',
                'worker_id' => 'require',
            ], [
                'id.require' => 'id不能为空！',
                'worker_id.require' => 'worker_id不能为空！',
            ]);
            $validate->check($data) || $this->error($validate->getError());

            $flag = Db::name('store_apply_record')->where(['id'=>$data['id'],'status'=>1])->find();
            if(!$flag) $this->error('已经被处理或者被删除');
            Db::startTrans();
            $res[] = DataService::other_save('store_apply_record',[$data['field']=>$data['value'],'worker_id'=>$data['worker_id']],['id'=>$data['id']]);
            if($data['value'] == 2){
                $memberInfo = Db::name('store_member')->where(['id'=>$flag['uid']])->find();
                $flag_shares = Db::name('bags_log')->where(['fromid'=>$memberInfo['id'],'uid'=>$memberInfo['first_leader']])->find();
                if(!$flag_shares){
                    $res['upgrade_user'] = DataService::other_save('store_member',['member_level'=>2],['id'=>$flag['uid']]);
                    if($memberInfo['first_leader'] > 0){
                        $res['giveshare'] = mlog($memberInfo['first_leader'],'spread_integral',sysconf('share_spread_integral'),"您的团队{$memberInfo['nickname']}升级成为VIP",'share_spread_integral','','',$memberInfo['id']);
                    }
                }
                if (input('type') == 'full'){
                    $res[] = mlog($flag['uid'],'integral',$flag['num'],'申请全价保养赠送积分:'.$flag['num'],'give_integral');
                }elseif (input('type') == 'half'){
                    $res[] = mlog($flag['uid'],'spread_used',$flag['num'],'用户使用半价积分:'.$flag['num'],'use_integral');
                }

            }
            if(input('type') == 'half'){
                $res[] = DataService::other_save('store_member',['is_half_price'=>1],['id'=>$flag['uid']]);
            }elseif(input('type') == 'full'){
                $res[] = DataService::other_save('store_member',['is_full_price'=>1],['id'=>$flag['uid']]);
            }else{
                $this->error('未知类型');
            }

//            $res = Db::name('store_member')->where('id',$flag['uid'])->update(['is_full_price'=>1]);
            if(check_arr($res)){
                Db::commit();
                $this->success('操作成功','');
            }else{
                Db::rollback();
                $this->error('网络故障,操作失败');
            }
        }
        return view();
    }

    public function user_balance()
    {
        if($this->request->post()){
            $data = $this->request->post();
            if($data['member_id']){
                $userInfo = Db::name('store_member')->where('id',$data['member_id'])->find();

                $content_str = '';
                if($data['recharge_type'] ==1){
                    if($data['integral'] > $userInfo['integral']) $this->error('用户积分不足');
                    $content_str = "后台减少用户:{$data['member_id']},积分:{$data['integral']}";
                    $data['integral'] = '-'.$data['integral'];
                }else{
                    $content_str = "后台增加用户:{$data['member_id']},积分:{$data['integral']}";
                    $data['integral'] = $data['integral'];
                }
                Db::startTrans();
                $res = mlog($data['member_id'],'integral',$data['integral'],$content_str,'20');
                if(check_arr($res)){
                    Db::commit();
                    return $this->success('操作成功','');
                }else{
                    Db::rollback();
                    return $this->error('操作失败');
                }
            }else{
                return $this->error('账户不存在！');
            }
        }
        return view();
    }

    

    public function backadd(){
        $data = input('post.');
        $validate = Validate::make([
            'id' => 'require',
            'worker_id' => 'require',
        ], [
            'id.require' => 'id不能为空！',
            'worker_id.require' => 'iworker_id不能为空！',
        ]);
        $validate->check($data) || $this->error($validate->getError());

        $flag = Db::name('store_apply_record')->where(['id'=>$data['id'],'status'=>1])->find();
        if(!$flag) $this->error('已经被处理或者被删除');
        Db::startTrans();
        $res[] = DataService::other_save('store_apply_record',[$data['field']=>$data['value'],'worker_id'=>$data['worker_id']],['id'=>$data['id']]);
        if($data['value'] == 2){
            $memberInfo = Db::name('store_member')->where(['id'=>$flag['uid']])->find();
            $flag_shares = Db::name('bags_log')->where(['fromid'=>$memberInfo['id'],'uid'=>$memberInfo['first_leader']])->find();
            if(!$flag_shares){
                $res['upgrade_user'] = DataService::other_save('store_member',['member_level'=>2],['id'=>$flag['uid']]);
                if($memberInfo['first_leader'] > 0){
                    $res['giveshare'] = mlog($memberInfo['first_leader'],'spread_integral',sysconf('share_spread_integral'),"您的团队{$memberInfo['nickname']}升级成为VIP",'share_spread_integral','','',$memberInfo['id']);


                }
            }
            $res[] = mlog($flag['uid'],'integral',$flag['num'],'申请全价保养赠送积分:'.$flag['num'],'give_integral');
        }
        $res[] = DataService::other_save('store_member',['is_full_price'=>1],['id'=>$flag['uid']]);
        if(check_arr($res)){
            Db::commit();
            $this->success('操作成功','');
        }else{
            Db::rollback();
            $this->error('网络故障,操作失败');
        }
    }


    public function back(){
        $data = input('post.');
        $validate = Validate::make([
            'id' => 'require',
            'worker_id' => 'require',
        ], [
            'id.require' => 'id不能为空！',
            'worker_id.require' => 'iworker_id不能为空！',
        ]);
        $validate->check($data) || $this->error($validate->getError());

        $flag = Db::name('store_apply_record')->where(['id'=>$data['id'],'status'=>1])->find();
        if(!$flag) $this->error('已经被处理或者被删除');
        Db::startTrans();
        $res[] = DataService::other_save('store_apply_record',[$data['field']=>$data['value'],'worker_id'=>$data['worker_id']],['id'=>$data['id']]);
        if($data['value'] == 2){
            $memberInfo = Db::name('store_member')->where(['id'=>$flag['uid']])->find();
            $flag_shares = Db::name('bags_log')->where(['fromid'=>$memberInfo['id'],'uid'=>$memberInfo['first_leader']])->find();
            if(!$flag_shares){
                $res['upgrade_user'] = DataService::other_save('store_member',['member_level'=>2],['id'=>$flag['uid']]);
                if($memberInfo['first_leader'] > 0){
                    $res['giveshare'] = mlog($memberInfo['first_leader'],'spread_integral',sysconf('share_spread_integral'),"您的团队{$memberInfo['nickname']}升级成为VIP",'share_spread_integral','','',$memberInfo['id']);


                }
            }
            $res[] = mlog($flag['uid'],'integral',$flag['num'],'申请全价保养赠送积分:'.$flag['num'],'give_integral');
        }
        $res[] = DataService::other_save('store_member',['is_half_price'=>1],['id'=>$flag['uid']]);
        if(check_arr($res)){
            Db::commit();
            $this->success('操作成功','');
        }else{
            Db::rollback();
            $this->error('网络故障,操作失败');
        }
    }


    public function half()
    {
        $this->title = '半价保养申请';
        $get = $this->request->get();

        $db = Db::table('store_apply_record a')
            ->join('store_member b',"a.uid = b.id")
            ->field('a.*,b.phone,b.nickname')
            ->where(['a.type'=>'is_half_price']);
        /*$db = Db::name('store_apply_record')
            ->alias('a')
            ->join('store_member b','a.uid = b.id')
            ->where("a.type",'is_half_price')
            ->select();
        dump($db);
        die;*/

        /*if($this->user['id'] != 10000) {
            if (strlen($this->shopUnderUsers) > 0 || empty($this->shopUnderUsers)) {
                $db->where('b.id', 'in', $this->shopUnderUsers);
            }
        }*/

        if (isset($get['create_at']) && $get['create_at'] !== '') {
            list($start, $end) = explode(' - ', $get['create_at']);
            $db->whereBetween('a.addtime', ["{$start} 00:00:00", "{$end} 23:59:59"]);
        }

        if (isset($get['nickname']) && $get['nickname'] !== '') {
            $db->where('b.nickname', 'like',"%{$get['nickname']}%");
        }

        if (isset($get['phone']) && $get['phone'] !== '') {
            $db->where('b.phone', 'like',"%{$get['phone']}%");
        }
        $db->where('a.shopid', $this->user['id']);
        return parent::_list($db->order('a.addtime desc'));
    }

}
